package com.example.commons.filter;

import com.example.commons.utils.JwtTokenService;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(urlPatterns = "/api/*",filterName = "CorsFilter") // 或使用其他方式注册过滤器
public class JwtFilter implements Filter {
    private JwtTokenService jwtTokenService;
    public void setJwtTokenService(JwtTokenService jwtTokenService) {
        this.jwtTokenService = jwtTokenService;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletResponse res = (HttpServletResponse) response;
        if ("OPTIONS".equals(((HttpServletRequest) request).getMethod())) {
            // 预检请求
            res.addHeader("Access-Control-Allow-Origin", "*");
            res.setHeader("Access-Control-Allow-Methods", "*"); // 或者列出具体允许的方法如"GET, POST, PUT, DELETE"
            res.setHeader("Access-Control-Allow-Headers", "*"); // 或者列出实际请求中会发送的特定头部
            res.setHeader("Access-Control-Allow-Credentials", "true");
            // 对于预检请求，不需要调用后续的过滤器和控制器
            return;
        }
        res.setHeader("Access-Control-Allow-Origin","*");

        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String requestURI = httpServletRequest.getRequestURI();
        if (requestURI.endsWith("/login") || requestURI.endsWith("/login/") || requestURI.endsWith("/enrollInfoList") || requestURI.endsWith("/bindChildren") || requestURI.indexOf("/stuEnroll")>0 || requestURI.indexOf("/bindTeacher")>0 || requestURI.startsWith("/api/images/") || requestURI.startsWith("/api/upload") || requestURI.startsWith("/api/notToken")) { // 根据你的实际路径调整
            // 放行登录请求，不执行JWT验证
            chain.doFilter(request, response);
        } else {
            String authorizationHeader = httpServletRequest.getHeader("Authorization");
            // 对非登录请求执行JWT验证
            if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
                try {
                    String token = authorizationHeader.substring(7); // 去掉"Bearer "前缀
                    String username = jwtTokenService.getUsernameFromToken(token);
                    if (jwtTokenService.validateToken(token, username)) {
                        // 验证成功，设置用户信息到request属性或其他上下文中
                        request.setAttribute("username", username);
                        chain.doFilter(request, response);
                    } else {
                        ((HttpServletResponse) response).sendError(HttpServletResponse.SC_UNAUTHORIZED, "登录失效,请重新登录");
                    }
                } catch (Exception e) {
                    ((HttpServletResponse) response).sendError(HttpServletResponse.SC_UNAUTHORIZED, "登录失效,请重新登录");
                }
            } else {
                ((HttpServletResponse) response).sendError(HttpServletResponse.SC_UNAUTHORIZED, "系统繁忙，稍后重试");
            }
        }
    }
}